<template>
  <div class="profile-container">
    <el-container>
      <el-header>
        <div class="header-container">
          <div class="logo">管理系统</div>
          <div class="user-info">
            <el-dropdown @command="handleCommand">
              <span class="el-dropdown-link">
                {{ authStore.user?.username || '用户' }}
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="home">返回首页</el-dropdown-item>
                  <el-dropdown-item command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-header>
      
      <el-container>
        <el-aside width="200px">
          <el-menu
            default-active="/profile"
            class="el-menu-vertical"
            router
          >
            <el-menu-item index="/">
              <el-icon><HomeFilled /></el-icon>
              <span>首页</span>
            </el-menu-item>
            <el-menu-item index="/profile">
              <el-icon><User /></el-icon>
              <span>个人信息</span>
            </el-menu-item>
          </el-menu>
        </el-aside>
        
        <el-main>
          <el-card>
            <template #header>
              <div class="card-header">
                <h2>个人信息</h2>
              </div>
            </template>
            
            <el-descriptions title="基本信息" :column="1" border>
              <el-descriptions-item label="用户名">{{ authStore.user?.username || '-' }}</el-descriptions-item>
              <el-descriptions-item label="用户ID">{{ authStore.user?.id || '-' }}</el-descriptions-item>
              <el-descriptions-item label="用户角色">{{ roleText }}</el-descriptions-item>
              <el-descriptions-item label="注册时间">{{ authStore.user?.created_at || '-' }}</el-descriptions-item>
            </el-descriptions>
          </el-card>
          
          <el-card class="password-card">
            <template #header>
              <div class="card-header">
                <h2>修改密码</h2>
              </div>
            </template>
            
            <el-form :model="passwordForm" :rules="rules" ref="passwordFormRef" label-width="100px">
              <el-form-item label="原密码" prop="oldPassword">
                <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入原密码" />
              </el-form-item>
              
              <el-form-item label="新密码" prop="newPassword">
                <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" />
              </el-form-item>
              
              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" />
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" :loading="authStore.loading" @click="handleChangePassword">修改密码</el-button>
                <el-button @click="resetForm">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script lang="ts" setup>
import { computed, reactive, ref, onMounted } from 'vue'
import { useAuthStore } from '@/store/auth'
import { useRouter } from 'vue-router'
import { ArrowDown, HomeFilled, User } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

const authStore = useAuthStore()
const router = useRouter()

// 角色文本
const roleText = computed(() => {
  const role = authStore.userRole
  switch (role) {
    case 0:
      return '普通用户'
    case 1:
      return '管理员'
    case 2:
      return '超级管理员'
    default:
      return '未知角色'
  }
})

// 密码表单ref
const passwordFormRef = ref<FormInstance>()

// 密码表单数据
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码一致性验证
const validatePass = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入新密码'))
  } else if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

// 表单验证规则
const rules = reactive<FormRules>({
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度应不少于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validatePass, trigger: 'blur' }
  ]
})

// 下拉菜单命令处理
const handleCommand = (command: string) => {
  if (command === 'logout') {
    authStore.logout()
  } else if (command === 'home') {
    router.push('/')
  }
}

// 处理修改密码
const handleChangePassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      const success = await authStore.changePassword({
        old_password: passwordForm.oldPassword,
        new_password: passwordForm.newPassword
      })
      
      if (success) {
        resetForm()
        ElMessage.success('密码修改成功，请使用新密码重新登录')
        setTimeout(() => {
          authStore.logout()
        }, 1500)
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields()
  }
}

// 组件挂载时检查认证状态
onMounted(() => {
  authStore.checkAuth()
})
</script>

<style scoped>
.profile-container {
  height: 100%;
}

.el-header {
  background-color: #409EFF;
  color: white;
  line-height: 60px;
  padding: 0 20px;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo {
  font-size: 18px;
  font-weight: bold;
}

.user-info {
  display: flex;
  align-items: center;
}

.el-dropdown-link {
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.el-aside {
  background-color: #f5f7fa;
  color: #333;
  border-right: 1px solid #e6e6e6;
}

.el-menu {
  border-right: none;
}

.el-main {
  background-color: #f5f7fa;
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.password-card {
  margin-top: 20px;
}
</style> 